from fastapi import FastAPI, APIRouter
from typing import Dict
import uvicorn


# 1. 创建基于类的视图
class UserViews:
    def __init__(self, router: APIRouter):
        self.router = router
        # 1. 类初始化
        self.count = 0
        # 2. 注册路由
        self.router.add_api_route("/", self.index_html, methods=["GET"], response_model=Dict[str, str])

    # 路由处理方法
    def index_html(self):
        self.count += 1
        return {"Hello": f"count={self.count}"}


# 2. 应用组装
def create_app() -> FastAPI:
    app = FastAPI(title="FastAPI Class-Based Views Example")

    # 创建一个 APIRouter 实例，并设置公共前缀和标签
    # user_router = APIRouter(prefix="/users", tags=["users"])
    user_router = APIRouter()

    # 实例化我们的视图类，并将 router 传入
    UserViews(user_router)

    # 将 APIRouter 挂载到主应用上
    app.include_router(user_router)

    @app.get("/")
    def root():
        return {"message": "Welcome to the User API. See /docs for documentation."}

    return app


def main():
    app = create_app()
    # 使用 Uvicorn 运行 FastAPI 应用
    uvicorn.run(app, host="127.0.0.1", port=8090)


if __name__ == "__main__":
    main()

""" 
不带前缀: http://localhost:8090/
带前缀: http://localhost:8090/users/
"""